package com.cmcc.shared.viewModel

import android.annotation.SuppressLint
import android.app.Application
import android.os.CountDownTimer
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.cmcc.shared.R
import com.cmcc.shared.config.SharedConfig
import com.cmcc.shared.data.PlatformRequest
import com.cmcc.shared.model.*
import com.cmcc.shared.utils.L
import com.cmcc.shared.utils.TokenUtils
import com.cmcc.shared.utils.showToast
import com.google.firebase.iid.FirebaseInstanceId
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class SharedViewModel(application: Application) : AndroidViewModel(application) {

    companion object {
        val loginToken = MutableLiveData<NetToken>()
    }

    var processOrder = MutableLiveData<OrderRecord>()

    var driverWorkStatus = MutableLiveData<AppResponse<Int>>()

    val carInfo =  MutableLiveData<CardInfo>()

    var isShowBookOver = MutableLiveData(Pair("", false))

    private var startBookTimer: CountDownTimer? = null

    private var step = 0
    private var listDriverTrice = Vector<DriverTrice>()
    @SuppressLint("SimpleDateFormat")
    fun uploadBatch(token: String = TokenUtils.getUserToken(), coordinatesXY: CoordinatesXY) {
        step++
        if (step%6 == 0) {
            listDriverTrice.add(DriverTrice(
                coordinates = coordinatesXY,
                createTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()),
                idCard = SharedConfig.cardId
            ))
        }
        if (SharedConfig.isorderDoing && step % 36 == 0) {
            viewModelScope.launch(Dispatchers.IO) {
                try {
                    val response =
                        PlatformRequest.getInstance().uploadBatch("Bearer $token", listDriverTrice)
                    if (response.code() == 200) {
                        listDriverTrice.clear()
                    }
                } catch (e: Exception) {
                    L.d("e :" + e.message + "," + e.cause)
                }
            }
        }
    }

    /*
    * 预约单倒计时
    * */
    fun bookCountDownTimer(token: String = TokenUtils.getUserToken(), role: Int) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response =
                    PlatformRequest.getInstance().queryOrderInProgress("Bearer $token", role)
                if (response.isSuccessful) {
                    val post = response.body()

                    if (post?.data?.type == 2) {//预约单
                        post.data.startTime?.let {
                            var format: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            var startDate: Date = format.parse(it)

                            var nowTime: Date = Date()
                            var timeGap = startDate.time - nowTime.time
                            if (timeGap > 0) {
                                if (startBookTimer == null) {
                                    startBookTimer = object : CountDownTimer(timeGap, 1000L) {
                                        override fun onTick(millisUntilFinished: Long) {

                                        }

                                        override fun onFinish() {
                                            isShowBookOver.postValue(Pair(post.data.id ?: "", true))
                                        }
                                    }.start()
                                }
                            } else {
                                isShowBookOver.postValue(Pair(post.data.id ?: "", true))
                            }
                        }
                    }
                } else {
                    L.d("server error")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }


    /**
     * 登录
     */
    fun userLogin(fireBaseToken: String, myLinkToken: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = PlatformRequest.getInstance()
                    .userLogin(myLinkToken, fireBaseToken)
                if (response.isSuccessful) {
                    val res = response.body()
                    if (res?.code == 200) {
                        //token 进行持久化
                        loginToken.postValue(res.data)
                        TokenUtils.setUserToken(res.data.token)
                    } else {
//                        showToast(
//                            getApplication(),
//                            getApplication<Application>().resources.getString(R.string.user_info_failed_tip)
//                        )
                    }
                } else {
                    L.d("response failed：userLogin")
//                    showToast(
//                        getApplication(),
//                        getApplication<Application>().resources.getString(R.string.user_info_failed_tip)
//                    )
                }

            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
//                showToast(
//                    getApplication(),
//                    getApplication<Application>().resources.getString(R.string.user_info_failed_tip)
//                )
            }
        }
    }

    fun requestCardInfo(token: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = PlatformRequest.getInstance()
                    .getCardInfo("Bearer $token")
                if (response.isSuccessful) {
                    val res = response.body()
                    if (res?.code == 200) {
                        carInfo.postValue(res.data)
                    }
                } else {
                    L.d("response failed：getCardInfo")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    /**
     * 查询正在进行的订单
     */
    fun queryOrderProgress(token: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = PlatformRequest.getInstance().queryOrderInProgress("Bearer $token")
                if (response.isSuccessful) {
                    val post = response.body()
                    processOrder.value = post?.data
                } else {
                    L.d("server error")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    /**
     * 司机上下班
     */
    fun changeDriverStatus(
        token: String,
        status: Int,
        coordinates: Coordinates
    ) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = PlatformRequest.getInstance()
                    .changeDriverStatus("Bearer $token", status, coordinates)
                if (response.isSuccessful) {
                    val body = response.body()
                    driverWorkStatus.value = body
                } else {
                    L.d("response failed")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun userLogin(myLinkToken: String) {
        FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val fireBaseToken = task.result?.token
                    if (fireBaseToken.isNullOrBlank()) {
                        showToast(
                            getApplication(),
                            getApplication<Application>().resources.getString(R.string.google_service_failed_tip)
                        )
                    } else {
//                        val myLinkToken = SdkManager.getMyLinkToken()
                        if (myLinkToken.isNullOrBlank()) {
//                            showToast(
//                                getApplication(),
//                                getApplication<Application>().resources.getString(R.string.user_info_failed_tip)
//                            )
                        } else {
                            userLogin(fireBaseToken, myLinkToken)
                        }
                    }
                } else {
                    L.d("getInstanceId failed", task.exception.toString())

                    showToast(
                        getApplication(),
                        getApplication<Application>().resources.getString(R.string.google_service_failed_tip)
                    )
                }
            }
    }
}